#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

__author__ = "Yunpeng Li <ypli.chn@outlook.com.com>"

from EU.models import SpotType
from EU.models import Spot
import logging
import json

def get_spot_type_list():
    """
    获取景点类型列表
    :return: 类型数组
    """
    result = []
    type_list = SpotType.objects.filter(is_open=1)
    for type in type_list:
        result.append({
            "id":type.id,
            "image":type.image,
            "type":type.type,
    })
    logging.info("获取%d个景点类型",len(type_list))
    return json.dumps(result)

def search_spot(key):
    """
    搜索景点
    :param key: 关键字
    :return: 景点数组
    """
    result = []
    spot_list = Spot.objects.filter(name__icontains=key)
    for spot in spot_list:
        result.append({
            "id":spot.id,
            "type":spot.spot_type.type,
            "name":spot.name,
            "image":spot.picture.name,
            "longitude":spot.longitude,
            "latitude":spot.latitude,
            "score":spot.score,
        })
    print(result)
    return json.dumps(result)

def get_spot_list(type,start,num):
    """
    获取景点列表
    :param type: 经典类型
    :param start: 起始索引
    :param num:  景点个数
    :return: 景点数组
    """

    try:

        start = int(start)
        num = int(num)
    except TypeError as e:
        print("类型错误")

    if start<0:
        raise AttributeError("Attribute(start) must bigger than 0 ")



    result = []
    if num >= 0:
        spot_list = Spot.objects.filter(spot_type_id=type)[start:start+num]
    else:
        spot_list = Spot.objects.filter(spot_type_id=type)[start:]

    for spot in spot_list:
        result.append({
            "id":spot.id,
            "type":spot.spot_type.type,
            "name":spot.name,
            "image":spot.picture.name,
            "longitude":spot.longitude,
            "latitude":spot.latitude,
            "score":spot.score,
        })
    print(result)
    return json.dumps(result)

def get_spot(spot_id):
    """
    获取景点详细信息
    :param spot_id: 景点id
    :return: 景点信息dict
    """
    result = {}
    try:
        spot = Spot.objects.get(id=spot_id)
    except Exception as e:
        logging.error("数据库错误",e)
    else:
        result = {
            "id":spot.id,
            "name":spot.name,
            "latitude":spot.latitude,
            "longitude":spot.longitude,
            "type":spot.spot_type.type,
            "image":spot.picture.name,
            "score":spot.score,
            "introduction":spot.introduction,
            "voice":spot.voice_introduce.name,
        }
    return json.dumps(result)

def get_all_spot():
    result = []
    spot_type_list = SpotType.objects.all()
    for spot_type in spot_type_list:
        result.append({
            "id":spot_type.id,
            "type":spot_type.type,
            "is_open":spot_type.is_open,
        })
    return json.dumps(result)

def main():
    pass


if __name__ == '__main__':
    main()
